import axios from "axios";
import { message } from "antd";
import useAuthStore from "@/store/authStore.js";



// 创建axios实例
const service = axios.create({
  baseURL:
    import.meta.env.VITE_APP_USE_MOCK === "true"
      ? import.meta.env.VITE_MOCK_API_BASE_URL
      : import.meta.env.VITE_API_BASE_URL,
  timeout: 10000,
  headers: {
    "Content-Type": "application/json;charset=utf-8",
  },
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 从 Zustand store 中获取 token
    const token = useAuthStore.getState().token;
    if (token) {
      config.headers["Authorization"] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code === 200) {
      return res;
    } else if (res.code === 401) {
      // 使用 Zustand store 清除认证信息
      useAuthStore.getState().clearAuth();
      // 未授权，清除认证信息并跳转到登录页
      window.location.href = "/login";
      return Promise.reject(res);
    } else {
      message.error(res.message || "请求失败");
      return Promise.reject(res);
    }
  },
  (error) => {
    console.log("err:", error); // 修正字符串拼接
    let messageText = "";
    const status = error.response?.status;

    if (status === 401) {
      messageText = "未授权，请重新登录";
      // 使用 Zustand store 清除认证信息
      useAuthStore.getState().clearAuth();
      window.location.href = "/login"; // ✅ 直接强制跳转
    } else {
      switch (status) {
        case 403:
          messageText = "拒绝访问";
          break;
        case 404:
          messageText = "请求错误,未找到该资源";
          break;
        case 500:
          messageText = "服务器端出错";
          break;
        default:
          messageText = "网络连接错误";
      }
    }
    message.error(messageText);
    return Promise.reject(error);
  }
);

// 导出方法保持不变
export function get(config, url, params) {
  return service({ ...config, url, method: "GET", params });
}

export function post(config, url, data) {
  return service({ ...config, url, method: "POST", data });
}

export function put(config, url, data) {
  return service({ ...config, url, method: "PUT", data });
}

export function del(config, url, data) {
  return service({ ...config, url, method: "DELETE", data });
}
